
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>


<!-- 使用国内CDN加速 -->
<script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
<!-- 在JSP页面的head或body底部添加 -->
<script src="${pageContext.request.contextPath}/js/notification.js?v=3"></script>
<html>
<head>
    <script src="js/jquery-2.0.2.min.js"></script>
    <script src="${pageContext.request.contextPath}/js/jquery-2.0.2.min.js"></script>
    <title>${user.username} 的个人主页</title>
    <link rel="icon" href="./favicon/favicon.ico" type="image/x-icon">
    <!-- 使用国内CDN加速 -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.11.1/font/bootstrap-icons.min.css">
    <script src="js/jquery-2.0.2.min.js"></script>
    <script src="js/bootstrap.bundle.min.js"></script>
    <style>
        .profile-header{background:#f8f9fa;border-radius:.5rem;padding:1.5rem}
        .exp-bar{background:#e9ecef;border-radius:5px;height:10px;overflow:hidden;margin-top:5px}
        .exp-bar div{background:#0d6efd;height:100%;transition:width .3s}
    </style>
</head>
<body class="container mt-4">

<!-- ===== 个人信息卡片（无头像） ===== -->
<div class="profile-header d-flex justify-content-between align-items-center mb-4">
    <!-- 左侧：名称 + 经验值 -->

    <div>
        <h4 class="mb-0">${user.username}</h4>

        <%--经验值--%>
        <small class="text-muted">经验值:${experiencePoints}</small>
        <!-- 添加经验值刷新按钮（可选） -->
        <button class="btn btn-sm btn-outline-info" onclick="refreshExperience()">
            <i class="bi bi-arrow-repeat"></i>
        </button>
    </div>

    <div class="d-flex align-items-center mt-2">
    <!-- 关注 -->
    <a href="${pageContext.request.contextPath}/followeeServlet?method=findFolloweeList&followeeId=${user.id}"
       class="text-decoration-none me-4">
        <div class="fw-bold fs-5 text-primary" id="followeeCountDisplay">${followeeCount}</div>
        <div class="small text-muted">关注</div>
    </a>

    <!-- 粉丝 -->
    <a href="${pageContext.request.contextPath}/followeeServlet?method=findFanList&followeeId=${user.id}"
       class="text-decoration-none me-4">
        <div class="fw-bold fs-5 text-danger" id="fanCountDisplay">${fanCount}</div>
        <div class="small text-muted">粉丝</div>
    </a>

    <!-- 收藏按钮（所有人可见） -->
    <a href="${pageContext.request.contextPath}/articleServlet?method=findFavoriteList&userId=${user.id}"
       class="text-decoration-none">
        <div class="fw-bold fs-5 text-warning">
            <i class="bi bi-bookmark-star"></i> 收藏
        </div>
    </a>
    </div>



    <!-- 按钮区：作者自己 vs 访客 -->
    <div class="d-flex align-items-center gap-2"> <!-- 使用d-flex和gap-2来创建水平布局和按钮间距 -->
        <c:choose>
            <c:when test="${isOwner}">
                <div class="btn-group" role="group"> <!-- 使用btn-group来创建按钮组 -->
                    <a class="btn btn-outline-primary" href="${pageContext.request.contextPath}/userServlet?method=findById&id=${sessionScope.user.id}">
                        个人资料
                    </a>
                    <button class="btn btn-success" onclick="openWriteModal()">
                        <i class="bi bi-pencil-square"></i> 写博客
                    </button>
                    <button class="btn btn-secondary"
                            onclick="location.href='${pageContext.request.contextPath}/articleServlet?method=findByUserIdStatus'">
                        <i class="bi bi-file-earmark-text"></i> 草稿箱
                    </button>
                </div>
            </c:when>
            <c:otherwise>
                <div class="btn-group" role="group">
                    <c:set var="isFollowed" value="${not empty sessionScope.user and
                            not empty followeeService.findByUserIdAndFolloweeId(sessionScope.user.id, user.id)}" />

                    <button id="followBtn" class="btn ${isFollowed ? 'btn-secondary' : 'btn-primary'}"
                            onclick="toggleFollowAjax(${user.id})">
                        <i class="bi ${isFollowed ? 'bi-check' : 'bi-person-plus'}"></i>
                        <span>${isFollowed ? '已关注' : '关注'}</span>
                    </button>
                    <button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#sendMsgModal">
                        <i class="bi bi-envelope"></i> 私信
                    </button>
                </div>
            </c:otherwise>
        </c:choose>
    </div>





    <c:if test="${not empty followCount && followCount > 0}">
        <div class="mt-2">
            <a href="javascript:void(0)" onclick="showFollowers()" class="text-decoration-none">
                <i class="bi bi-people"></i> ${followCount} 人关注
            </a>
        </div>
        <!-- 关注列表弹窗 -->
        <div class="modal fade" id="followersModal" tabindex="-1">
            <div class="modal-dialog modal-sm">
                <div class="modal-content">

                    <div class="modal-header">
                        <h6 class="modal-title">关注 ${user.username} 的人</h6>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>

                    <div class="modal-body">
                        <c:forEach items="${followers}" var="f">
                            <div class="mb-1">
                                <a href="articleServlet?method=userProfile&userId=${user.id}">${user.username}</a>
                            </div>
                        </c:forEach>
                    </div>
                </div>
            </div>
        </div>
    </c:if>
</div>
<!-- 文章列表 -->
<div id="articleList">

    <c:forEach items="${articles}" var="article">
        <div class="card mb-3 shadow-sm">
            <div class="card-body">
                <!-- 标题 -->
                <a class="card-title fw-bold d-block mb-1" href="articleServlet?method=findByTitle&id=${article.id}">
                        ${article.title}
                </a>
                <!-- 内容摘要 -->
                <div class="text-muted small mb-2">
                        ${fn:substring(article.content, 0, 100)}...
                </div>
                <!-- 底部一行：时间 + 点赞 + 收藏 + 编辑 + 删除 -->
                <div class="d-flex justify-content-between align-items-center flex-wrap">
                    <!-- 左侧时间 -->
                    <small class="text-muted">${article.createdAt}</small>
                    <!-- 右侧按钮：点赞、收藏、编辑、删除 -->
                    <div>


    <span>
            <!-- 点赞 -->
                <button class="btn btn-sm btn-outline-primary like-btn ${article.userLiked ? 'btn-active' : ''}" onclick="start(${article.id})"
                        data-id="${article.id}">
                <i class="bi bi-hand-thumbs-up"></i>
             <span class="like-count" id="startCount${article.id}">${article.startCount}</span>
            </button>

        <!-- 收藏 -->
                <button class="btn btn-sm btn-outline-warning favorite-btn ms-2 ${article.userFavorited ? 'btn-favorite-active' : ''}" onclick="favorite(${article.id})"
                        data-id="${article.id}">
            <i class="bi bi-star"></i>
             <span class="favorite-count" id="favoriteCount${article.id}">${article.favoriteCount}</span>
            </button>
    </span>



    <!-- 删除按钮（仅作者可见） -->
                        <c:if test="${article.canDelete}">
                            <button class="btn btn-sm btn-danger"
                                    onclick="deleteArticle(${article.id})">删除</button>
                        </c:if>
                        <c:if test="${article.canDelete}">
                        <button class="btn btn-sm btn-warning edit-btn"
                                data-id="${article.id}"
                                data-title="${fn:escapeXml(article.title)}"
                                data-content="${fn:escapeXml(article.content)}"
                                onclick="showEditModal(this)">编辑
                        </button>
                        </c:if>
                    </div>
                </div>
            </div>
        </div>
    </c:forEach>

    <c:if test="${empty articles}">
        <div class="text-center text-muted">没有更多内容了</div>
    </c:if>
</div>


<!-- 私信模态框 -->
<div class="modal fade" id="sendMsgModal" tabindex="-1">
    <div class="modal-dialog">
        <form id="sendMsgForm" action="${pageContext.request.contextPath}/messageServlet?method=addMessage" method="post">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">写私信</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <input type="hidden" name="receiverId" value="${user.id}">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label" for="msgContent">内容</label>
                        <textarea class="form-control" id="msgContent" name="content" rows="3" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">发送</button>
                </div>
            </div>
        </form>
    </div>
</div>


<!-- 写博客弹窗 -->
<div class="modal fade" id="writeModal" tabindex="-1">
    <div class="modal-dialog">
        <form action="articleServlet?method=addArticle" method="post" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">写博客</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="status" value="1">
                <div class="mb-3">
                    <label class="form-label">标题</label>
                    <input type="text" class="form-control" name="title" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">正文</label>
                    <textarea class="form-control" name="content" rows="5" required></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-secondary" name="status" value="0">存稿</button>
                <button type="submit" class="btn btn-primary" name="status" value="1">发布</button>
            </div>
        </form>
    </div>
</div>

<!-- 草稿箱弹窗 -->
<div class="modal fade" id="draftModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">草稿箱</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="draftList">
                    <!-- Ajax 动态渲染区域 -->
                </div>
                <c:if test="${empty drafts}">
                    <div class="text-center text-muted">暂无草稿</div>
                </c:if>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">关闭草稿箱</button>
            </div>
        </div>
    </div>
</div>


<!-- 编辑文章模态框 -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <form id="editForm" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑文章</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="id" id="editArticleId">
                <div class="mb-3">
                    <label class="form-label">标题</label>
                    <input type="text" class="form-control" name="title" id="editTitle" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">正文</label>
                    <textarea class="form-control" name="content" id="editContent" rows="5" required></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>


<script>
    /* 打开弹窗 */
    function openWriteModal() { new bootstrap.Modal('#writeModal').show(); }
    function openDraftModal() { new bootstrap.Modal('#draftModal').show(); }

    function toggleFollowAjax(userId) {
        const btn = document.getElementById('followBtn');
        const isFollowed = btn.classList.contains('btn-secondary'); // 当前是否已关注

        $.post('followeeServlet?method=addFollowee&followeeId=' + userId)
            .done(function () {
                if (isFollowed) {
                    // 取消关注：变回蓝色
                    btn.classList.remove('btn-secondary');
                    btn.classList.add('btn-primary');
                    btn.innerHTML = '<i class="bi bi-person-plus"></i> 关注';
                } else {
                    // 添加关注：变灰色
                    btn.classList.remove('btn-primary');
                    btn.classList.add('btn-secondary');
                    btn.innerHTML = '<i class="bi bi-check"></i> 已关注';
                }
            })
            .fail(function () {
                alert("操作失败，请稍后重试");
            });
    }


    $(function () {
        const targetUserId = $('#targetUserId').val(); // 获取目标用户的 id

        $.get('followeeServlet?method=getFolloweeCount&userId=' + targetUserId)
            .done(count => $('#followeeCountDisplay').text(count));

        $.get('followeeServlet?method=getFanCount&userId=' + targetUserId)
            .done(count => $('#fanCountDisplay').text(count));
    });


    function showEditModal(button) {
        const id = $(button).data('id');
        const title = $(button).data('title');
        const content = $(button).data('content');

        $('#editArticleId').val(id);
        $('#editTitle').val(title);
        $('#editContent').val(content);

        new bootstrap.Modal(document.getElementById('editModal')).show();
    }




    function sendPrivateMessage() {
        var receiverId = $('#targetUserId').val(); // 获取接收者ID
        var content = $('#msgContent').val(); // 获取输入的内容
        if (content.trim() === '') {
        alert('请输入私信内容');
        return;
    }
        // 发送私信到服务器
        $.post('messageServlet', {
        receiverId: receiverId,
        content: content
    }, function(response) {
        if (response === 'success') {
        alert('私信发送成功');
        // 关闭模态框并返回个人主页
        $('#sendMsgModal').modal('hide');
        window.location.href = "${pageContext.request.contextPath}/userProfile.jsp?userId=" + receiverId;
    } else {
        alert('发送失败，请重试');
    }
    });
    }

        // 打开写私信模态框的函数
        function openSendMsgModal() {
        $('#sendMsgModal').modal('show');
    }

        // 绑定私信按钮点击事件
        $('#sendMsgBtn').click(function() {
        openSendMsgModal();
    });


    // 编辑按钮点击事件
    $(document).on('click', '.edit-btn', function() {
        var id = $(this).data('id');
        var title = $(this).data('title');
        var content = $(this).data('content');

        $('#editArticleId').val(id);
        $('#editTitle').val(title);
        $('#editContent').val(content);

        new bootstrap.Modal('#editModal').show();
    });

    // 编辑表单提交
    $('#editForm').submit(function(e) {
        e.preventDefault();
        $.post('${pageContext.request.contextPath}/articleServlet?method=update', $(this).serialize())
            .done(function() {
                location.reload(); // 刷新页面
            })
            .fail(function() {
                alert('更新失败');
            });
    });




    function toggleFollowAjax(userId) {
        const btn = document.getElementById('followBtn');
        const isFollowed = btn.classList.contains('btn-secondary'); // 当前是否已关注

        $.post('followeeServlet?method=addFollowee&followeeId=' + userId)
            .done(function () {
                if (isFollowed) {
                    // 取消关注：变回蓝色
                    btn.classList.remove('btn-secondary');
                    btn.classList.add('btn-primary');
                    btn.innerHTML = '<i class="bi bi-person-plus"></i> 关注';
                } else {
                    // 添加关注：变灰色
                    btn.classList.remove('btn-primary');
                    btn.classList.add('btn-secondary');
                    btn.innerHTML = '<i class="bi bi-check"></i> 已关注';
                }
            })
            .fail(function () {
                alert("操作失败，请稍后重试");
            });
    }

    function toggleFollow(userId, isFollowed) {
        if (isFollowed) {
            // 取消关注
            location.href = 'followeeServlet?method=addFollowee&followeeId=' + userId;
        } else {
            // 添加关注
            location.href = 'followeeServlet?method=addFollowee&followeeId=' + userId;
        }
    }

    function openDraftModal() {
        $.get('${pageContext.request.contextPath}/articleServlet?method=findByUserIdStatus', function (list) {
                 let html = '';
            list.forEach(d => {
                html += `
              <div class="card mb-2">
                <div class="card-body d-flex justify-content-between">
                  <a href="articleServlet?method=draftDetail&id=${d.id}" class="fw-bold">${d.title}</a>
                  <small class="text-muted">${d.createdAt}</small>
                </div>
              </div>`;
            });
            $('#draftList').html(html || '<div class="text-center text-muted">暂无草稿</div>');
            new bootstrap.Modal('#draftModal').show();
        });
    }

    function toggleAction(id, type) {
        $.post(`article/${type}/${id}`)
            .done(function (data) {
                // data: {"count":12,"active":true}
                const btn = $(`.${type}-btn[data-id=${id}]`);
                btn.find('span').text(data.count);
                btn.toggleClass('btn-outline-primary active', type === 'like');
                btn.toggleClass('btn-outline-warning active', type === 'favorite');
            });
    }



    function start(id) {
        $.post('articleServlet?method=start&id=' + id)
            .done(function (data) {
                let obj = JSON.parse(data);
                if (obj.error) {
                    alert(obj.error);
                    return;
                }

                // 更新点赞数
                $('#startCount' + id).text(obj.count);

                // 更新按钮样式
                let btn = $('.like-btn[data-id="' + id + '"]');
                if (obj.liked) {
                    btn.addClass('btn-active');
                } else {
                    btn.removeClass('btn-active');
                }
                btn.find('i').toggleClass('bi-hand-thumbs-up-fill', obj.liked);

            })
            .fail(function () {
                alert("请求失败");
            });
    }

    function favorite(id) {
        $.post('articleServlet?method=favorite&id=' + id)
            .done(function (data) {
                let obj = JSON.parse(data);
                if (obj.error) {
                    alert(obj.error);
                    return;
                }

                // 更新收藏数
                $('#favoriteCount' + id).text(obj.count);

                // 更新按钮样式
                let btn = $('.favorite-btn[data-id="' + id + '"]');
                if (obj.liked) {
                    btn.addClass('btn-favorite-active');
                    btn.removeClass('btn-outline-primary');
                } else {
                    btn.removeClass('btn-favorite-active');
                    btn.addClass('btn-outline-primary');
                }
                btn.find('i').toggleClass('bi-star-fill', obj.liked);

            })
            .fail(function () {
                alert("请求失败");
            });
    }


    function follow(userId){
        location.href = 'followeeServlet?method=addFollowee&followeeId=' + userId;
    }


    $('#sendMsgBtn').click(function () {
        const he = $('#targetUserId').val();
        // 直接跳转到聊天页面
        location.href = 'chat.jsp?with=' + he + '&withName=' + encodeURIComponent("${user.username}");
    });


    // 经验值刷新函数
    function refreshExperience() {
        $.get('${pageContext.request.contextPath}/followeeServlet', {
            method: 'getExperiencePoints',
            id: ${user.id}
        }, function(data) {
            $('#experiencePointsDisplay').text(data);
        });
    }

    // 页面加载时自动刷新经验值
    $(document).ready(function() {
        refreshExperience();
    });


    function deleteArticle(id) {
        if (confirm('确定删除这篇文章吗？')) {
            location.href = '<%=request.getContextPath()%>/articleServlet?method=delete&id=' + id;
        }
    }

</script>
</body>
</html>